<template>
    <div ref="tooltipRef" class="pe-tooltip" @mouseenter="show = true" @mouseleave="show = false">
        <slot></slot>
        <Teleport to="body">
            <Transition name="tooltip">
                <div v-if="show" ref="tooltipItemRef" class="pe-popup pe-tooltip-item" :style="{
                    padding: '5px',
                    backgroundColor: effect === 'dark' ? '#000000' : '#ffffff', color: effect === 'dark' ? '#ffffff' : '#000000', zIndex,
                    borderColor: effect === 'dark' ? '#000000' : 'var(--pe-color-border)', inset: `${insetTop} ${insetRight} ${insetBottom} ${insetLeft}`
                }">
                    <slot name="content">
                        <div v-if="rawContent" v-html="content"></div>
                        <div v-else>{{ content }}</div>
                    </slot>
                    <div class="pe-popup-triangle" :style="{
                        backgroundColor: effect === 'dark' ? '#000000' : '#ffffff', borderColor: effect === 'dark' ? '#000000' : 'var(--pe-color-border)',
                        inset: `${triangleTop} ${triangleRight} ${triangleBottom} ${triangleLeft}`, transform: rotate
                    }">
                    </div>
                </div>
            </Transition>
        </Teleport>
    </div>
</template>

<script setup lang="ts">
import { watch, ref, inject, onMounted } from "vue"
import { getInset } from "../../utils/popupUtil"

interface Props {
    effect?: 'dark' | 'light',
    content?: string,
    rawContent?: boolean,
}

withDefaults(defineProps<Props>(), {
    effect: "light",
    rawContent: false,
})

const tooltipRef = ref<HTMLDivElement>()
const tooltipItemRef = ref<HTMLDivElement>()

// 出现标志
const show = ref<boolean>(true)

// z-index
const zIndex: any = inject("pe-z-index")
watch(show, newShow => {
    if (newShow) {
        zIndex.value++
    }
})

// 元素定位
const insetTop = ref<string>("auto")
const insetRight = ref<string>("auto")
const insetBottom = ref<string>("auto")
const insetLeft = ref<string>("auto")
// 三角定位
const triangleTop = ref<string>("auto")
const triangleRight = ref<string>("auto")
const triangleBottom = ref<string>("auto")
const triangleLeft = ref<string>("auto")
const rotate = ref<string>("")

onMounted(() => {
    getPosition()
    const insetObj = getInset(tooltipRef, tooltipItemRef, false)
    insetTop.value = insetObj.insetTop
    insetRight.value = insetObj.insetRight
    insetBottom.value = insetObj.insetBottom
    insetLeft.value = insetObj.insetLeft
    triangleTop.value = insetObj.triangleTop
    triangleRight.value = insetObj.triangleRight
    triangleBottom.value = insetObj.triangleBottom
    triangleLeft.value = insetObj.triangleLeft
    rotate.value = insetObj.rotate
})

const getPosition = () => {
    console.log(tooltipRef.value?.offsetWidth);
}

</script>

<script lang="ts">
export default {
    name: "pe-tooltip"
}
</script>
